//
//  HomePageDetailViewController.m
//  Taste
//
//  Created by 徐昊 on 16/9/18.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "HomePageDetailViewController.h"
#import "ZWYNetTool.h"
#import "HXMacro.h"
#import "UIImageView+WebCache.h"
#import "HomePageDetailModel.h"
#import "HomePageDetailRes.h"
#import "NSString+Vali.h"
#import "HomePageDetailContent.h"
#import "UIView+Frame.h"
#import "HomePageDetailTableViewCell.h"
#import "SelfSizeTool.h"
#import "VideoWebViewController.h"

#define kHomePageDetailWebTableViewCellName @"HomePageDetailWebTableViewCellNameReuse"
#define kHomePageDetailImageTableViewCellName @"HomePageDetailImageTableViewCellNameReuse"
#define kHomePageDetailAddressTableViewCellName @"HomePageDetailAddressTableViewCellNameReuse"
#define kHomePageDetailTableViewCell @"HomePageDetailTableViewCellReuse"
@interface HomePageDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UIImageView *headerPic;
@property (weak, nonatomic) IBOutlet UILabel *headerTitle;
@property (weak, nonatomic) IBOutlet UILabel *headerPosition;
@property (weak, nonatomic) IBOutlet UILabel *headerCategory;
@property (nonatomic, strong) HomePageDetailModel *model;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIImageView *video;

@property (nonatomic, strong) NSString *webString;

@end

@implementation HomePageDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _tableView.delegate = self;
    _tableView.dataSource = self;
    NSString *string = [NSString stringWithFormat:@"id=%@", _numString];
    NSString *num = [NSString stringWithFormat:@"%ld", [string length]];
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : num};
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=info&a=getinfo" andBody:string andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [HomePageDetailModel modelWithDic:result];
        _headerTitle.text = _model.res.title;
        _headerPosition.text = _model.res.authorname;
        _headerCategory.text = _model.res.HomePageDetail_typeid;
        if ([_headerCategory.text isEqualToString:@"3"]) {
            _headerCategory.text = @"餐厅";
        }
        if ([_headerCategory.text isEqualToString:@"6"]) {
            _headerCategory.text = @"秘籍";
        }
        if ([_headerCategory.text isEqualToString:@"11"]) {
            _headerCategory.text = @"八卦";
        }
        if ([_headerCategory.text isEqualToString:@"9"]) {
            _headerCategory.text = @"热点";
        }
        if ([_headerCategory.text isEqualToString:@"2"]) {
            _headerCategory.text = @"专栏";
        }
        if ([_headerCategory.text isEqualToString:@"16"]) {
            _headerCategory.text = @"酒";
        }
        if ([_headerCategory.text isEqualToString:@"10"]) {
            _headerCategory.text = @"寻味";
        }
        [_headerPic sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:_model.res.pic]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        if ([_model.res.video isEqualToString:@""]) {
            _video.alpha = 0;
        } else {
            _video.alpha = 1;
            _headerPic.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(push)];
            [_headerPic addGestureRecognizer:tap];
        }
        // 对webView内容进行拼接
        [self handleContent];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    [_tableView registerNib:[UINib nibWithNibName:@"HomePageDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kHomePageDetailTableViewCell];

}
- (void)push {
    VideoWebViewController *vc = [[VideoWebViewController alloc] init];
    vc.urlStr = _model.res.video;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)handleContent {
    _webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);
    _webView.backgroundColor = [UIColor cyanColor];
    _webView.delegate = self;
    _webView.scrollView.bounces = NO;
    _webView.scrollView.showsHorizontalScrollIndicator = NO;
    _webView.scrollView.scrollEnabled = NO;
    [_webView sizeToFit];
    _webString = [NSString string];
    for (int i = 0; i < _model.res.content.count; i++) {
        if (_model.res.content[i].type == 0) {
            _webString = [_webString stringByAppendingString:_model.res.content[i].txt];
        }
        if (_model.res.content[i].type == 1) {
            NSString *string = [NSString stringWithFormat:@"%@%@", _model.res.content[i].host, _model.res.content[i].pic];
            NSString *webString = [NSString imageWebWithStr:string];
            NSString *headStr = @"<img width=\"100%\" src=\"";
            NSString *tailStr = @"\"/>";
            webString = [NSString stringWithFormat:@"%@%@%@", headStr, webString, tailStr];
            _webString = [_webString stringByAppendingString:webString];
        }
    }
    _webView.dataDetectorTypes = UIDataDetectorTypeAll;
    NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", _webString];
    [_webView loadHTMLString:htmlcontent baseURL:nil];
}
- (IBAction)pop:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return SCREEN_WIDTH / 3 + 50;
    } else {
        return (SCREEN_WIDTH / 3 + 50) * 2;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        HomePageDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kHomePageDetailTableViewCell];
        if (indexPath.section == 0) {
            if (_model.res.latestCon.count != 0) {
                cell.latestCon = _model.res.latestCon;
            }
        } else if (indexPath.section == 1) {
            if (_model.res.more.count != 0) {
                cell.more = _model.res.more;
            }
        }
        return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *string = nil;
    if (section == 0) {
        string = @"今日更新";
    } else if (section == 1) {
        string = @"更多";
    }
    return string;
}
#pragma mark - 计算webView高度
-(void)webViewDidFinishLoad:(UIWebView *)webView
{    //获取页面高度（像素）
    NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];
    float clientheight = [clientheight_str floatValue];
    //设置到WebView上
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, clientheight);
    //获取WebView最佳尺寸（点）
    CGSize frame = [webView sizeThatFits:webView.frame.size];
    //获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    float height = [height_str floatValue] - 20;
    //内容实际高度（像素）* 点和像素的比
    height = height * frame.height / clientheight;
    //再次设置WebView高度（点）
    webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
    _webView.frame = CGRectMake(0, 5, SCREEN_WIDTH, height);
    _headerView.h_height = [SelfSizeTool selfSizeHeightWith:_model.res.title width:self.view.h_width - 63 font:[UIFont systemFontOfSize:20]] + [SelfSizeTool selfSizeHeightWith:_model.res.authorname width:self.view.h_width - 63 font:[UIFont systemFontOfSize:15]] + SCREEN_WIDTH + _webView.h_height;
    _tableView.tableHeaderView = _headerView;
    [_tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
